﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MShop.Core.Domain;
using MShop.Web.Components;
using MShop.Core.DataAccess;

namespace MShop.Web.Areas.Admin.Controllers
{
    public class MenuController : SecureController
    {
         private readonly IItemCatDao _ItemCatDao;
         private readonly IMenuDao _MenuDao;
         public MenuController(IItemCatDao itemcatdao,IMenuDao menuDao)
        {
            _ItemCatDao = itemcatdao;
            _MenuDao = menuDao;
        }

        public ActionResult Index()
        {
            ViewData["menus"] = _MenuDao.Build();
           // BuildMenuTree();
            return View();
        }

        public void InitMenuListItem(object selectedValue=null)
        {
            ViewData["Menus"] = _MenuDao.BuildSelectList(selectedValue, true);      

        }
 
        public ActionResult Edit(int? id)
        {
          
            Menu menu = new Menu();
            if (id.HasValue)
            {
                menu = _MenuDao.GetById(id);
                
                InitMenuListItem(menu.ParentId);
               
            }
            else
            {
                InitMenuListItem(id);
            }
            return View(menu);
        }

        //
        // POST: /Menu/Edit/5

        [HttpPost]
        public ActionResult Edit(int? id,Menu menu, FormCollection collection)
        {
            if (id.HasValue)
            {
                var menu2 = _MenuDao.GetById(id);
                menu2.Name = menu.Name;
                menu2.ParentId = menu.ParentId;
                menu2.Code = menu.Code;
                menu2.Icon = menu.Icon;
                menu2.Url = menu.Url;
                _MenuDao.SaveChanges();
            }
            else
            {  
                _MenuDao.Save(menu);
                _MenuDao.SaveChanges();
            }
        

            return RedirectToAction("Index");
             
        }

        //
        // GET: /Menu/Delete/5
 
        public ActionResult Delete(int id)
        {
            var menu = _MenuDao.GetById(id);          
            _MenuDao.Delete(menu);
            _MenuDao.SaveChanges();
            return RedirectToAction("index");
            
        }

        
    }
}
